package com.ucode.hrm.controller;

import com.ucode.hrm.controller.dto.HrmExcelCompareResult;
import com.ucode.hrm.controller.service.ApiHrmExcelHandleService;
import com.ucode.springboot.starter.operatelog.core.annotations.UcodeOperateLogBp;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Tag(name = "管理后台 - 人力资源系统 - Excel对比工具")
@RestController
@RequestMapping("/hrm/excel-tool")
@Validated
public class HrmExcelCompareController {

    @Resource
    private ApiHrmExcelHandleService apiHrmExcelHandleService;

    @PostMapping("/compare")
    @Operation(summary = "差异对比")
    @UcodeOperateLogBp(enable = false) //没有记录操作日志的必要
    public ResponseEntity<byte[]> compareExcelSheets(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "keyColumn", defaultValue = "0") int keyColumnIndex) {

        try {
            HrmExcelCompareResult result = apiHrmExcelHandleService.compareExcelSheets(file, keyColumnIndex);
            
            // 使用UriUtils正确编码文件名
            String encodedFilename = UriUtils.encodePath(result.getFilename(), StandardCharsets.UTF_8);
            String contentDisposition = "attachment; filename=" + encodedFilename;

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(result.getContent());
        } catch (UcodeServiceException e) {
            throw e;
        } catch (Exception e) {
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED.getCode(),"处理Excel文件时发生错误");
        }
    }


}